﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Brower
{
    public class ShopCarController : BaseController
    {

        private static IShopCar _shopCarAccess;
        private static IProductPreview _productPreView;
        private static IUser _userAccess;

        public ShopCarController()
        {
            _shopCarAccess = DataBaseExecuter.CreateClassByName<IShopCar>("ShopCarAccess");
            _productPreView = DataBaseExecuter.CreateClassByName<IProductPreview>("ProductPreView");
            _userAccess = DataBaseExecuter.CreateClassByName<IUser>("UserAccess");

        }
        /// <summary>
        /// 一加载就判断用户是否登录合并购物车
        /// </summary>
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            this.SiteMapPathAdd("首页" , "/");
            this.SiteMapPathAdd("所有商品" , Url.Action("ProductList" , "Product"));
            this.SiteMapPathAdd("用户中心" , Url.Action("Index" , "Customer"));
            //合并购物车
            if (User.Identity.IsAuthenticated)
                this.MergeShopCar();
        }

        #region 购物车

        /// <summary>
        /// 我的购物车
        /// </summary>
        public ActionResult ShopCar()
        {
            this.SiteMapPathAdd("购物车");
            ShopCarViewModel _viewMode = new ShopCarViewModel() { ImageRoot = _imageRoot };
            _viewMode.CarList = User.Identity.IsAuthenticated
                ? _shopCarAccess.CarList(_user.Uid , (int)ShopCarType.ShopCar)
                : GetCookCar();

            return View(_viewMode);
        }
        /// <summary>
        /// 迷你购物车
        /// </summary>
        public ActionResult MiNiCar()
        {
            ViewData["ImageRoot"] = _imageRoot;
            return View(
                User.Identity.IsAuthenticated
                ? _shopCarAccess.CarList(_user.Uid , (int)ShopCarType.ShopCar)
                : GetCookCar());
        }
        /// <summary>
        /// 增加到购物车
        /// </summary>
        [HttpPost]
        public ActionResult AddToCar(
            [DefaultValue(0)]int productId
            , [DefaultValue(1)]int count)
        {
            MessageHelper msg = new MessageHelper("shopcar");
            msg.AddBody(4);
            msg.DefaultOperate("javascript:CloseDialog()");
            // 从cookie中获取购物车
            List<ProductEntity> cookieCar = GetCookCar();
            // 参数检查
            if (productId > 0)
            {
                // 附加可选参数
                string optional = string.Empty;
                if (Request.Form["optional"] != null)
                {
                    //对参选进行排序，以防止管理员调整了参数排序属性错乱
                    var optionals = Request.Form.GetValues("optional").OrderBy(i => Convert.ToInt32(i));
                    foreach (string i in optionals)
                    {
                        optional += string.Format("{0}," , i);
                    }
                    optional = optional.Trim(',');
                }

                if (!User.Identity.IsAuthenticated)
                {
                    #region 查找元素在列表中的索引

                    int index = -1;
                    var c = cookieCar.Where((item , innerIndex) =>
                    {
                        if (item.ProductId == productId && item.KeyWords == optional)// 提示信息:用户自定属性存放于KeyWords
                        {
                            index = innerIndex;
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }).FirstOrDefault();

                    if (c != null)
                    {
                        cookieCar[index].SalesCount += count;
                    }
                    else
                    {
                        //  cookie中没有发现产品增加该产品
                        cookieCar.Add(new ProductEntity()
                        {
                            ProductId = productId ,
                            SalesCount = count ,
                            KeyWords = optional // 提示信息:用户自定属性存放于KeyWords
                        });
                    }

                    #endregion

                    this.WriteCookCar(cookieCar);
                }
                else
                {
                    int result = _shopCarAccess.AddToCar(new ShopCarEntity()
                    {
                        Uid = _user.Uid ,
                        ProductId = productId ,
                        Property = optional ,
                        Count = count ,
                        Description = "" ,
                        CartType = (int)ShopCarType.ShopCar
                    });
                }
                msg.AddOperate("查看购物车" , Url.Action("ShopCar" , "ShopCar"));
                msg.AddMessage(4);
            }
            else
            {
                msg.AddBody(3);
                msg.AddMessage(5);
            }
            return MessageResult(msg.CreateMessage() , ResultType.Ajax);
        }
        /// <summary>
        /// 保存购物车
        /// </summary>
        [HttpPost]
        public ActionResult ShopCar([DefaultValue(false)]bool setpNext)
        {
            if (Request.Form["ProductId"] != null)
            {
                string[] ids = Request.Form.GetValues("ProductId");
                string[] counts = Request.Form.GetValues("Count");
                // 提示，这里加入自选属性是因为购物车并没有主键，因此进行修改删除的时候需要同时提供ID和可选属性
                string[] optionals = Request.Form.GetValues("optional");

                List<ProductEntity> cookieCar = GetCookCar();

                for (int i = 0 ; i < ids.Length ; i++)
                {
                    int productId , count;
                    int.TryParse(ids[i] , out productId);
                    int.TryParse(counts[i] , out count);

                    // 参数检查
                    if (productId <= 0)
                        break;


                    if (!User.Identity.IsAuthenticated)
                    {


                        #region 查找元素在列表中的索引

                        int index = -1;
                        var c = cookieCar.Where((item , innerIndex) =>
                        {
                            if (item.ProductId == productId && item.KeyWords == optionals[i])// 提示性说明，用户自定义属性存放于KeyWords
                            {
                                index = innerIndex;
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }).FirstOrDefault();

                        if (c != null)
                        {
                            cookieCar[index].SalesCount = count;
                            // 购买数量为0时从购物车删除
                            if (count < 1)
                                cookieCar.RemoveAt(index);
                        }
                        #endregion

                        this.WriteCookCar(cookieCar);

                    }
                    else
                    {

                        _shopCarAccess.UpdateCar(
                          productId
                           , count
                           , optionals[i]
                           , _user.Uid
                           , (int)ShopCarType.ShopCar
                           );
                    }

                }
            }
            return setpNext
                ? RedirectToAction("ShopCar2")
                : RedirectToAction("ShopCar");

        }
        /// <summary>
        /// 移动购物车到收藏夹
        /// </summary>
        public ActionResult MoveToFavorite(
            int productId = 0
            , string Optional = "")
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Write(JavaScriptHelper.Alert(null , AlertType.RedirectToURL , Url.Action("Login" , "Home" , new { returnUrl = Request.UrlReferrer })));
            }
            else
            {
                Response.Write(JavaScriptHelper.Alert(null , AlertType.SpecifiedProcess , "location.reload();"));
                _shopCarAccess.MoveToType(new ShopCarEntity()
                {
                    Uid = _user.Uid ,
                    ProductId = productId ,
                    Description = string.Empty ,
                    Property = Optional ,
                    CartType = (int)ShopCarType.ShopCar
                } , (int)ShopCarType.Favorites);
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 删除购物车
        /// </summary>
        [HttpPost]
        public ActionResult DeleteCarItem(
            [DefaultValue(0)]int productId
            , [DefaultValue("")]string optional/* 提示，这里加入自选属性是因为购物车并没有主键，因此进行修改删除的时候需要同时提供ID和可选属性*/)
        {

            if (User.Identity.IsAuthenticated)
            {
                int result = _shopCarAccess.DeleteCar(productId , optional , _user.Uid , (int)ShopCarType.ShopCar);
            }
            else
            {

                #region 查找元素在列表中的索引

                List<ProductEntity> cookieCar = GetCookCar();
                int index = -1;
                var c = cookieCar.Where((item , innerIndex) =>
                {
                    // 购物车提示信息：用自定义属性存放于KeyWords属性
                    if (item.ProductId == productId && item.KeyWords == optional)
                    {
                        index = innerIndex;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }).FirstOrDefault();

                if (c != null)
                {
                    cookieCar.RemoveAt(index);
                }

                #endregion

                // 写入cookie
                this.WriteCookCar(cookieCar);
            }
            return new EmptyResult();
        }

        #endregion


        #region 增加到订单
        /// <summary>
        /// 关联收货人地址
        /// </summary>
        [Authorize()]
        public ActionResult ShopCar2()
        {
            this.SiteMapPathAdd("购物车" , Url.Action("ShopCar" , "ShopCar"));
            this.SiteMapPathAdd("填写收货地址");
            CustomerViewModel _viewModel = new CustomerViewModel();
            _viewModel.AddressBookList = _userAccess.AddressBookList(_user.Uid);
            return View(_viewModel);
        }
        /// <summary>
        /// 增加到订单
        /// </summary>
        [HttpPost]
        [Authorize()]
        public ActionResult AddToOrder(
            UserAddressEntity shipAddress
               )
        {
            // 收货地址正确性检查
            MessageHelper msg = new MessageHelper("shopcar");
            msg.AddBody(1);
            msg.Required(shipAddress.ReallyName , 1);
            msg.Required(shipAddress.Address , 2);
            if (msg.IsValid)
            {
                shipAddress.Uid = _user.Uid;
                _userAccess.SaveAddressBook(shipAddress);
                //转到真正的增加订单
                return RedirectToAction("AddToOrder" , "Customer" , new { addressId = shipAddress.AddressId });
            }
            return MessageResult(msg.CreateMessage());

        }

        #endregion


        #region 收藏夹

        /// <summary>
        /// 收藏夹
        /// </summary>
        [Authorize()]
        public ActionResult Favorite()
        {
            this.SiteMapPathAdd("收藏夹");
            ShopCarViewModel viewModel = new ShopCarViewModel() { ImageRoot = _imageRoot };
            viewModel.CarList = _shopCarAccess.CarList(_user.Uid , (int)ShopCarType.Favorites);
            return View(viewModel);
        }
        /// <summary>
        /// 加入到收藏夹
        /// </summary>
        [HttpPost]
        public ActionResult AddToFavorite(int productId = 0)
        {

            MessageHelper msg = new MessageHelper("shopcar");

            // 加入收藏需要登录
            if (!User.Identity.IsAuthenticated)
            {
                msg.AddBody(5);
                msg.DefaultOperate(string.Format("javascript:{0}" , JavaScriptHelper.Alert(string.Empty , AlertType.RedirectToURL , Url.Action("Login" , "Home" , new { returnUrl = Request.UrlReferrer }))));
                msg.AddMessage(6);
                msg.AddOperate("登录" , Url.Action("Login" , "Home" , new { returnUrl = Request.UrlReferrer }));
            }
            else
            {

                msg.AddBody(6);
                msg.DefaultOperate("javascript:CloseDialog()");
                msg.AddMessage(4);

                _shopCarAccess.AddToCar(new ShopCarEntity()
                {
                    Count = 1 ,
                    ProductId = productId ,
                    Uid = _user.Uid ,
                    Description = string.Empty ,
                    Property = string.Empty ,
                    CartType = (int)ShopCarType.Favorites
                });
            }

            return MessageResult(msg.CreateMessage() , ResultType.Ajax);
        }
        /// <summary>
        /// 删除收藏夹项
        /// </summary>
        [HttpPost]
        [Authorize]
        public ActionResult DeleteFavoriteItem(
            int productId = 0
            , string Optional = "")
        {
            _shopCarAccess.DeleteCar(productId , Optional , _user.Uid , (int)ShopCarType.Favorites);
            return new EmptyResult();
        }

        #endregion


        #region 私有方法

        /// <summary>
        /// 将修正的购物车写入Cookie
        /// </summary>
        private void WriteCookCar(List<ProductEntity> cookieCar)
        {

            List<CookieCarEntity> carCookie = new List<CookieCarEntity>();
            foreach (ProductEntity item in cookieCar)
            {
                carCookie.Add(new CookieCarEntity()
                {
                    ProductId = item.ProductId ,
                    Count = item.SalesCount ,
                    Property = item.KeyWords // 购物车提示信息：用自定义属性存放于KeyWords属性
                });
            }

            JavaScriptSerializer json = new JavaScriptSerializer();

            Response.Cookies.Add(new HttpCookie(_shopCarCookieName)
            {
                Value = json.Serialize(carCookie) ,
                Expires = DateTime.Now.AddDays(6)
            });
        }
        /// <summary>
        /// 从cookie中反向存储的购物车数据
        /// </summary>
        /// <returns></returns>
        private List<ProductEntity> GetCookCar()
        {
            List<CookieCarEntity> carCookie;
            try
            {
                JavaScriptSerializer json = new JavaScriptSerializer();
                carCookie = json.Deserialize<List<CookieCarEntity>>(
                    Request.Cookies[_shopCarCookieName] != null
                    ? Request.Cookies[_shopCarCookieName].Value
                    : string.Empty)
                    ?? new List<CookieCarEntity>();
            }
            catch
            {
                carCookie = new List<CookieCarEntity>();
            }

            List<ProductEntity> cookieCar = new List<ProductEntity>();
            foreach (CookieCarEntity item in carCookie)
            {
                ProductEntity product = _shopCarAccess.CarList(item.ProductId , item.Property , (int)ShopCarType.ShopCar);
                if (product != null)
                {
                    product.SalesCount = item.Count;
                    cookieCar.Add(product);
                }
            }

            return cookieCar;
        }
        /// <summary>
        /// 合并购物车
        /// </summary>
        private void MergeShopCar()
        {
            List<ProductEntity> cookieCar = GetCookCar();
            foreach (ProductEntity item in cookieCar)
            {
                int result = _shopCarAccess.AddToCar(new ShopCarEntity()
                {
                    Uid = _user.Uid ,
                    ProductId = item.ProductId ,
                    Count = item.SalesCount ,
                    Property = item.KeyWords ,//核心提示，用户自定义属性存放在KeyWords里面
                    Description = "" ,
                    CartType = (int)ShopCarType.ShopCar
                });
            }
            Response.Cookies.Add(new HttpCookie(_shopCarCookieName) { Expires = DateTime.Now.AddDays(-1) });
        }

        #endregion



    }
}
